package com.xpgk.mvc.bstockHandover;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.interceptor.AuthInterceptor;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.productOutin.ProductOutin;
import com.xpgk.mvc.productSales.ProductSales;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.productStock.ProductStock;
import com.xpgk.mvc.productStock.ProductStockInfo;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolRandoms;
import com.xpgk.tools.security.ToolPbkdf2;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service(name = BstockHandoverService.serviceName)
public class BstockHandoverService  extends  BaseService {
	
	
	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(BstockHandoverService.class);
	public static final String serviceName = "bstockHandoverService";
	
	
	/**获取库存交接
	 * 
	 * @param orgids
	 * @return
	 */
	public  String  getStock(String orgids)
	{	
		List  kcjjList=new ArrayList<>();
		
		
		String pSql=getSqlMy(Product.sqlId_nolcpro);
		List<Product> pList = Product.dao.find(pSql,Code.lc_ids);
		//查出上一条交接记录
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", StockHandover.column_organIds);
		String sql = getSqlByBeetl(StockHandover.sqlId_column, param);
		List<StockHandover> shList = StockHandover.dao.find(sql,orgids);
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String newdate=dateFormater.format(new Date());
	
		
		float  sbNum=0;
		if(pList!=null && pList.size()>0)
		{	
			for(int i=0;i<pList.size();i++)
			{	
				Map  mm=new HashMap<>();
				//查询销售的map
				Map<String, Object> queryParam  =new HashMap<String, Object>();
				queryParam.put("productID", pList.get(i).getStr(Product.column_ids));
				queryParam.put("organIds", orgids);
				queryParam.put("endDate", newdate);
				//查询入库的map
				Map<String, Object> rukuParam  =new HashMap<String, Object>();
				rukuParam.put("productIds", pList.get(i).getStr(Product.column_ids));
				rukuParam.put("organIds", orgids);
				rukuParam.put("endDate", newdate);
				rukuParam.put("style", "0");
				//查询出库的map
				Map<String, Object> chukuParam  =new HashMap<String, Object>();
				chukuParam.put("productIds", pList.get(i).getStr(Product.column_ids));
				chukuParam.put("organIds", orgids);
				chukuParam.put("endDate", newdate);
				chukuParam.put("style", "1");
				

				if(shList!=null && shList.size()>0)
				{
					//存在上一条交接记录
					String stSql=getSqlMy(StockTransfer.sqlId_selByproIdsAndHanIds);
					StockTransfer st=StockTransfer.dao.findFirst(stSql,pList.get(i).getStr(Product.column_ids),shList.get(0).getStr(StockHandover.column_ids));
					if(st!=null)
					{
						sbNum=st.getFloat(StockTransfer.column_physicalInventory);
					}
					queryParam.put("startDate", shList.get(0).getDate(StockHandover.column_jjDate).toString());
					rukuParam.put("startDate", shList.get(0).getDate(StockHandover.column_jjDate).toString());
					chukuParam.put("startDate", shList.get(0).getDate(StockHandover.column_jjDate).toString());
				}
				List<Record> ps =find(ProductSales.sqlId_selByProAndDate,queryParam);
				List<Record> rupo =find(ProductOutin.sqlId_selByProAndDate,rukuParam);
				List<Record> chupo =find(ProductOutin.sqlId_selByProAndDate,chukuParam);
				
				String  stockSql=getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
				ProductStock  psp=ProductStock.dao.findFirst(stockSql,orgids,pList.get(i).getStr(Product.column_ids));
				mm.put("productids", pList.get(i).getStr(Product.column_ids));
				mm.put("productname", pList.get(i).getStr(Product.column_name));
				mm.put("typeids", pList.get(i).getType().getStr(Code.column_ids));
				mm.put("productclass", pList.get(i).getType().getStr(Code.column_name));
				mm.put("numberonwork", sbNum);
				if(ps.get(0).getBigDecimal("sum")!=null)
				{
					mm.put("usenumber", ps.get(0).getBigDecimal("sum").toString());
				}else
				{
					mm.put("usenumber", "0");
				}
				if(rupo.get(0).getBigDecimal("sum")!=null)
				{
					mm.put("instorage",  rupo.get(0).getBigDecimal("sum").toString());
				}else
				{
					mm.put("instorage",  "0");
				}
				if(chupo.get(0).getBigDecimal("sum")!=null)
				{
					mm.put("outstorage",  chupo.get(0).getBigDecimal("sum").toString());
				}else
				{
					mm.put("outstorage", "0");
				}
				if(psp!=null)
				{
					mm.put("stock", psp.getFloat(ProductStock.column_num));
					mm.put("actuallynumber", psp.getFloat(ProductStock.column_num));
				}else
				{
					mm.put("stock", "0");
					mm.put("actuallynumber", "0");
				}
				mm.put("difference", "0");
				mm.put("reasondifference", " ");
				kcjjList.add(mm);
			}
		}
		String json1 = JsonKit.toJson(kcjjList);
		json1 = "{\"total\":" + kcjjList.size() + ",\"rows\":" + json1 + "}";
		return  json1;
	}
	/**交接人和接班人密码验证
	 * 
	 * @param userIds
	 * @param password
	 * @return
	 */
	public String  verifyPassword(String  userIds,String  password)
	{
				// 1.取用户
				User user = User.dao.findById(userIds);
				if (null == user) {
					return "用户不存在！";// 用户不存在
				}

				// 2.停用账户
				String status = user.getStr(User.column_status);
				if (status.equals("0")) {
					return "账号已停用！";
				}

				// 3.验证密码
				String saltStr = user.get(User.column_salt); // 密码盐
				byte[] salt = Base64.decodeBase64(saltStr);
				String passStr = user.get(User.column_password); // 密码
				byte[] encryptedPassword = Base64.decodeBase64(passStr);
				boolean bool = false;
				try {
					bool = ToolPbkdf2.authenticate(password, encryptedPassword, salt);
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				} catch (InvalidKeySpecException e) {
					e.printStackTrace();
				}
				if (bool) {
					// 密码验证成功
					return ConstantRender.render_success_code;
				} else {
					return "密码错误！";
				}
	}
	
	
	/**保存库存交接
	 * 
	 * @param orgids
	 * @param sh
	 * @param stList
	 * @return
	 */
	public  String   saveStockHandover(String orgids,StockHandover  sh,List<StockTransfer> stList)
	{
		String msg=ConstantRender.render_success_code;
		
		if(sh!=null)
		{
			sh.set(StockHandover.column_organIds, orgids);
			if(!sh.save())
			{
				log.debug("保存库存交接单失败");
				throw new RuntimeException("保存库存交接单失败!");
			}
			if(stList!=null && stList.size()>0)
			{	
				for(StockTransfer st:stList)
				{
					st.set(StockTransfer.column_handoverIds, sh.getStr(StockHandover.column_ids))
						.set(StockTransfer.column_date, sh.getDate(StockHandover.column_jjDate));
					if(!st.save())
					{
						log.debug("保存库存交接单详细信息失败");
						throw new RuntimeException("保存库存交接单详细信息失败!");
					}
					String  sql=getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
					ProductStock  pst=ProductStock.dao.findFirst(sql,orgids,st.getStr(StockTransfer.column_productIds));
					if(pst!=null)
					{
						pst.set(ProductStock.column_num, st.getFloat(StockTransfer.column_physicalInventory))
							.set(ProductStock.column_gxsj, new Date());
						if(!pst.update())
						{
							log.debug("更新机构产品库存表失败");
							throw new RuntimeException("更新机构产品库存表失败!");
						}
					}else
					{
						ProductStock  pstock=new ProductStock();
						pstock.set(ProductStock.column_ids, ToolRandoms.getUuid(true))
								.set(ProductStock.column_organids, orgids)
								.set(ProductStock.column_productID, st.getStr(StockTransfer.column_productIds))
								.set(ProductStock.column_num, st.getFloat(StockTransfer.column_physicalInventory))
								.set(ProductStock.column_gxsj, new Date());
						if(!pstock.save())
						{
							log.debug("保存机构产品库存失败");
							throw new RuntimeException("保存机构产品库存失败!");
						}
						
					}
					//更新库存明细
					SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
			    	String gxsj="%"+dateFormater.format(new Date())+"%";
					String  psiSql=getSqlMy(ProductStockInfo.sqlId_selByOidsAndPidsAndTime);
					ProductStockInfo  psi=ProductStockInfo.dao.findFirst(psiSql,orgids,st.getStr(StockTransfer.column_productIds),gxsj);
					if(psi!=null)
			    	{	
			    		//库存详细信息减少库存
			    		psi.set(ProductStockInfo.column_stock,st.getFloat(StockTransfer.column_physicalInventory))
			    			.set(ProductStockInfo.column_gxsj, new Date());
			    		if(!psi.update())
			    		{
			    			log.debug("更新库存明细失败");
							throw new RuntimeException("更新库存明细失败!");
			    		}
			    		
			    	}else
			    	{
			    		ProductStockInfo psInfo=new ProductStockInfo();
			    		String psinfoids = ToolRandoms.getUuid(true);
			    		psInfo.set(ProductStockInfo.column_ids, psinfoids)
			    				.set(ProductStockInfo.column_organids, orgids)
			    				.set(ProductStockInfo.column_productID, st.getStr(StockTransfer.column_productIds))
			    				.set(ProductStockInfo.column_type,st.getStr(StockTransfer.column_typeIds))
			    				.set(ProductStockInfo.column_stock, st.getFloat(StockTransfer.column_physicalInventory))
			    				.set(ProductStockInfo.column_gxsj, new Date());
			    		if(!psInfo.save())
				    	{
			    			log.debug("保存产品库存记录失败！！");
				    		throw new RuntimeException("保存产品库存记录失败!");
				    	}	
			    	}
					
				}
				
			}
			
		}
		
		
		
		return  msg;
	}
	
}
